package com.hub.frame.service.security.impl;

import com.hub.utils.ApiResultObject;
import com.hub.utils.encrypt.AESUtil;
import com.hub.frame.consts.ConstantUtil;
import com.hub.frame.pojo.CachedUserInfo;
import com.hub.frame.pojo.Security;
import com.hub.frame.service.cache.ICached;
import com.hub.frame.service.security.IAuthService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author hub
 **/
@Service
public class AuthServiceImpl implements IAuthService {

    @Resource
    private ICached cached;

//    /**
//     * 身份认证信息保存
//     * @param openId
//     * @param sessionKey
//     * @throws Exception
//     * @return
//     */
//    @Override
//    public Security setAuthInfo(String openId, String sessionKey) throws Exception {
//        // 取得token并保存
//        String token = AESUtil.encrypt(openId, AESUtil.SECRET2);
//        cached.set("token_" + openId, token, (int)(ConstantUtil.TIME_SIGN_KEY/1000));
//
//        // sessionKey是用户加密后的用户信息
//        if(sessionKey!=null) {
//            cached.set("sessionKey_" + openId, sessionKey, (int)(ConstantUtil.TIME_SIGN_KEY/1000));
//        }
//
//        // 取得签名用的公钥并保存
//        String secret = AESUtil.getRandomSecret() + "";
//        cached.set("secret_" + openId, secret);
//        return new Security(token, secret);
//    }

    @Override
    public Security setAuthInfo(String userId, String roleId, String userName) throws Exception {
        // 取得token并保存
        String token = AESUtil.encrypt(userId, AESUtil.SECRET2);
//        cached.set("token_" + userId, token, ConstantUtil.TIME_SIGN_KEY);
        // 取得签名用的公钥并保存
        String secret = AESUtil.getRandomSecret() + "";
//        cached.set("secret_" + userId, secret);
        if(roleId == null) {
            roleId = "";
        }
//        cached.set(userId, roleId);
//        if(!StringUtils.isEmpty(userName)){
//            cached.set("userName_" + userId, userName);
//        }
//        cached.set(token, userId, 60);

        CachedUserInfo cachedObj = new CachedUserInfo();
        cachedObj.setUserId(userId);
        cachedObj.setUserName(userName);
        cachedObj.setRoleId(roleId);
        cached.set(token, cachedObj, ConstantUtil.TIME_SIGN_KEY);
        return new Security(token, secret);
    }

    @Override
    public ApiResultObject removeAuthInfo(String token) {
        cached.delete(token);
        return ApiResultObject.success();
    }
}
